/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nominalitzacions.ui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;



/**
 *
 * @author sonia.sandalinas
 */
public class PrincipalView extends JFrame {

    private PrincipalViewController PVC;

    // Variable Texto principal
    private JTextPane text = new JTextPane();
    private int horizontal = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER;
    private int vertical = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
    private JScrollPane scroller = new JScrollPane(text,vertical, horizontal);

    //Listas ComboBox
    private String[] s = {"12","14","16","18","20"};
    private String[] c = {"Green", "Blue", "Gray", "Black"};
    private GraphicsEnvironment fonts = GraphicsEnvironment.getLocalGraphicsEnvironment();
    private String[] f = fonts.getAvailableFontFamilyNames();
    private JLabel tamany = new JLabel("Size");
    private JComboBox size = new JComboBox(s);
    private JLabel fuente1 = new JLabel("Source");
    private JComboBox fuente = new JComboBox(f);
    private JLabel color2 = new JLabel("Color");
    private JComboBox color = new JComboBox(c);

    //Lista nominalizaciones
    //private JList list  = new JList(new DefaultListModel());

    //Menu
    private JMenuBar menuBar = new JMenuBar();

    private JMenu file = new JMenu("File");
        private JMenuItem new1 = new JMenuItem("New");
        private JMenu open = new JMenu ("Open");
            private JMenuItem text1 = new JMenuItem("Text");
            private JMenuItem project = new JMenuItem ("Project");
        private JMenu save = new JMenu("Save");
            private JMenuItem texts = new JMenuItem("Text");
            private JMenuItem projects = new JMenuItem("Project");
        private JMenuItem exit = new JMenuItem("Exit");
    private JMenu edit = new JMenu ("Edit");
        private JMenuItem idiom = new JMenuItem("Idiom");
        private JMenuItem corpus = new JMenuItem("Corpus");
        private JMenuItem dicc = new JMenuItem ("Dictionary");
        private JMenuItem conf = new JMenuItem("Configuration");
        private JMenuItem redef = new JMenuItem("ChangePassword");
    private JMenu help = new JMenu("Help");
        private JMenuItem man = new JMenuItem("Manual");
        private JMenuItem authors = new JMenuItem("Authors");
        private JMenuItem features = new JMenuItem("Features");


        private int lastPost = 0;
        private int n;

        private final Highlighter hilit;
        private final Highlighter.HighlightPainter painter;
        private JPopupMenu popupMenu;


    /*private JMenu apareance = new JMenu("Appareance");
        private JMenu background = new JMenu("background");
            private JMenuItem blue = new JMenuItem ("Blue");
            private JMenuItem red = new JMenuItem("Red");
            private JMenuItem yellow = new JMenuItem("Yellow");
            private JMenuItem green = new JMenuItem ("Green");
            private JMenuItem black = new JMenuItem ("Black");
            private JMenuItem white = new JMenuItem ("White");
            private JMenuItem gray = new JMenuItem ("Gray");*/

    //Botones
  //  private JButton idv = new JButton("VerbsIdentifier");
//    private JButton nmlt = new JButton("Nominalized");


    public PrincipalView(PrincipalViewController PVC) {
        this.PVC = PVC;
        
        iniComponents();
        hilit = new DefaultHighlighter();
        painter = new DefaultHighlighter.DefaultHighlightPainter(Color.RED);
        text.setHighlighter(hilit);
    }

    private void iniComponents() {
        iniFrame();
        iniAll();
        assigListeners();
    }

    private void iniFrame() {
        this.setSize(800,600);
        this.setTitle("nominalized");
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.setLayout(null);
    }

    private void iniAll(){
        //ComboBox
        size.setBounds(720,20,50,20);
        this.add(size);
        tamany.setBounds(680,20,50,30);
        this.add(tamany);
        size.setFocusable(false);
        fuente.setBounds(340,20,200,20);
        this.add(fuente);
        fuente.setFocusable(false);
        fuente1.setBounds(290,20,50,30);
        this.add(fuente1);
        fuente.setSelectedItem("Times New Roman");
        color.setBounds(590,20,80,20);
        this.add(color);
        color.setFocusable(false);
        color2.setBounds(550,20,50,30);
        this.add(color2);
        color.setSelectedItem("Black");

        //Jtextpane
        /*list.setBounds (550,50,200,450);
        Border borde;
        borde = BorderFactory.createEtchedBorder();
        list.setBorder(borde);
        this.add(list);*/
        text.setBounds(30,50, 740, 460);
        text.requestFocus();
        text.selectAll();
        scroller.setBounds(30, 50, 740, 460);
        this.add(scroller);
        text.requestFocusInWindow();

                //Menu
        setJMenuBar(menuBar);
        menuBar.add(file);
            file.add(new1);
            file.add(open);
                open.add(text1);
                open.add(project);
            file.add(save);
                save.add(texts);
                save.add(projects);
            file.add(exit);

        menuBar.add(edit);
            edit.add(idiom);
            edit.add(corpus);
            edit.add(dicc);
            edit.add(conf);
            edit.add(redef);

        menuBar.add(help);
            help.add(man);
            help.add(authors);
            help.add(features);



            //PopUps
            popupMenu = new JPopupMenu();
            popupMenu.add(new JMenuItem("Add"));
            popupMenu.add(new JPopupMenu.Separator());
            popupMenu.add( new JMenuItem("Clear"));
        int contador = 0;

        /*menuBar.add(apareance);
            apareance.add(background);
                background.add(white);
                background.add(yellow);
                background.add(red);
                background.add(green);
                background.add(blue);
                background.add(gray);
                background.add(black);
*/
        //Botones
     /*   idv.setBounds(200,520, 150, 20);
        this.add(idv);
        nmlt.setEnabled(false);
        nmlt.setBounds(360,520,150,20);
        this.add(nmlt);*/
    }

    private void assigListeners(){

        size.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent evento) {
                actionPerformedSize();
            }
        });

        fuente.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evento) {
                actionPeformedFont();
            }
        });

        color.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evento) {
                 actionPerformedColor();
            }
        });

  /*      blue.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evento) {
                actionPerformedChangeColor("blue");
            }

        });
        white.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evento) {
                actionPerformedChangeColor("white");
            }
        });
        yellow.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evento) {
                actionPerformedChangeColor("yellow");
            }
        });
        red.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evento) {
                actionPerformedChangeColor("red");

            }
        });
        green.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evento) {
                actionPerformedChangeColor("green");

            }
        });
        gray.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evento) {
                actionPerformedChangeColor("gray");

            }
        });
        black.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evento) {
                actionPerformedChangeColor("black");
            }
        });*/

        new1.addActionListener (new ActionListener() {
           public void actionPerformed(ActionEvent evento) {
              actionPerformedNewText();

           }
        });

        text1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evento) {
               actionPerformedOpenText();
            }
        });

        project.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent evento){
                actionPerformedOpenProject();
            }
        });
        texts.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent evento){
                actionPerformedSaveText();

            }
        });
        projects.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent evento){
                actionPerformedSaveProject();


            }
        });
        exit.addActionListener (new ActionListener() {
            public void actionPerformed( ActionEvent evento) {
                actionPerformedExit();

            }
        });
         /*nmlt.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evento) {
                actionPerformedNominalitzar();

            }
       });*/
       /*  idv.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evento) {
                    actionPerformedIdentifierVerbs();

                }
        });*/
        redef.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evento) {
                   actionPerformedRedefinir();
            }
        });
        /*idiom.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent evento) {
                actionPerformedIdiom();
            }
        });*/
        /*man.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent evento) {
                actionPerformedHelp("M");
            }
        });
        authors.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent evento) {
                actionPerformedHelp("A");
            }
        });
        features.addActionListener (new ActionListener() {
            public void actionPerformed (ActionEvent evento) {
                actionPerformedHelp("F");
            }
        });*/
       

        text.getDocument().addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e) {
                int n = text.getDocument().getLength();
                try {
                    if (n > 0) {
          
                        boolean espai = text.getDocument().getText(0,n).endsWith(" ");
                        boolean coma = text.getDocument().getText(0, n).endsWith(",");
                        boolean punticoma = text.getDocument().getText(0, n).endsWith(";");
                        boolean enter = text.getDocument().getText(0, n).endsWith("\n");
                        boolean punt = text.getDocument().getText(0, n).endsWith(".");
                        if (espai || coma || punticoma || enter || punt) {
                            String s = text.getDocument().getText(lastPost, n-lastPost-1);
                            System.out.println(s.trim());


                            boolean b = PVC.sendString(s);
                            if (s.equals("hola")) hilit.addHighlight(lastPost,n-1, painter);
                            

                            
                            /*else {
                                hilit.addHighlight(n, n, painter)
                            }*/
                            lastPost = n;

                        }

                    }

                } catch (BadLocationException ex) {
                    Logger.getLogger(PrincipalView.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
            public void removeUpdate(DocumentEvent e) {
               /* String s = text.getDocument().getText(lastPost, n-lastPost);
                            System.out.println(s.trim());
                            lastPost = n;*/

            }
            public void changedUpdate(DocumentEvent e) {
            
            }

        });
        conf.addActionListener(new ActionListener(){
            public void actionPerformed (ActionEvent evento){
                actionPerformedSetting();
            }
        });
        dicc.addActionListener(new ActionListener(){
            public void actionPerformed (ActionEvent evento) {
               // actionPerformedDictionary();
            }
        });
        text.addMouseListener(new MouseListener() {

            public void mouseClicked(MouseEvent e) {
                showpopup(e);
            }

            public void mousePressed(MouseEvent e) {
                showpopup(e);
            }

            public void mouseReleased(MouseEvent e) {
                showpopup(e);
            }

            public void mouseEntered(MouseEvent e) {
                showpopup(e);
            }

            public void mouseExited(MouseEvent e) {
                showpopup(e);
            }

        });

}

       
        /*text.addKeyListener(new KeyAdapter() {
            @Override
             public void keyPressed(KeyEvent evt) {
                 
                
            }
            });*/
    

    private void showpopup(MouseEvent e) {
        if (e.isPopupTrigger()) {
            popupMenu.setLocation(e.getLocationOnScreen());
            popupMenu.setVisible(true);
        }
    }

    private void actionPerformedSize(){
        String selec = (String) size.getSelectedItem();
        int sizeOne = Integer.valueOf(selec);
        MutableAttributeSet attr = new SimpleAttributeSet();
        StyleConstants.setFontSize(attr, sizeOne);
        text.setCharacterAttributes(attr, false);
    }
    private void actionPeformedFont(){
        String selec = (String) fuente.getSelectedItem();
        MutableAttributeSet attr = new SimpleAttributeSet();
        StyleConstants.setFontFamily(attr, selec);
        text.setCharacterAttributes(attr,false);
    }
    private void actionPerformedColor() {
        String selec = (String) color.getSelectedItem();
        Color nuevo = null;
        if (selec.equals("Green"))  nuevo = Color.GREEN;
        if(selec.equals("Blue"))   nuevo = Color.BLUE;
        if (selec.equals("Gray")) nuevo = Color.LIGHT_GRAY;
        if(selec.equals("Black")) nuevo = Color.BLACK;
        MutableAttributeSet attr = new SimpleAttributeSet();
        StyleConstants.setForeground(attr, nuevo);
        text.setCharacterAttributes(attr, false);
    }
    private void actionPerformedChangeColor(String carioca){
        if(carioca.equals("blue")) getContentPane().setBackground(Color.blue);
        if(carioca.equals("white"))getContentPane().setBackground(Color.WHITE);
        if (carioca.equals("yellow")) getContentPane().setBackground(Color.YELLOW);
        if(carioca.equals("red")) getContentPane().setBackground(Color.red);
        if(carioca.equals("green")) getContentPane().setBackground(Color.green);
        if(carioca.equals("gray")) getContentPane().setBackground(Color.LIGHT_GRAY);
        if(carioca.equals("black")) getContentPane().setBackground(Color.black);
    }

    private void actionPerformedNewText(){
        text.setText("");
    }
    private void actionPerformedOpenText(){
        JFileChooser otext = new JFileChooser();
               FileNameExtensionFilter filter = new FileNameExtensionFilter("archivos .txt", "txt");
               otext.setFileFilter(filter);
               int seleccion = otext.showOpenDialog(null);
               if (seleccion == JFileChooser.APPROVE_OPTION) {
                File file1 = otext.getSelectedFile();
                try {
                    BufferedReader entrada = new BufferedReader(new FileReader(file1));
                    try {
                        String linea = "";
                        while(entrada.ready()) {
                            linea += entrada.readLine() + System.getProperty("line.separator");

                        }
                        text.setText(linea);
                    } catch (IOException ex) {
                        Logger.getLogger(PrincipalView.class.getName()).log(Level.SEVERE, null, ex);
                    }

                } catch (FileNotFoundException ex) {
                    Logger.getLogger(PrincipalView.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
    }

    private void actionPerformedOpenProject(){
        JFileChooser otext = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("archivos .txt", "txt");
        otext.setFileFilter(filter);
        otext.showOpenDialog(null);
    }

    private void actionPerformedSaveText(){
           JFileChooser otext = new JFileChooser();
           FileNameExtensionFilter filter = new FileNameExtensionFilter("archivos .txt", "txt");
           otext.setFileFilter(filter);
           otext.showSaveDialog(null);
    }

    private void actionPerformedSaveProject() {
                JFileChooser otext = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter("archivos .txt", "txt");
                otext.setFileFilter(filter);
                otext.showSaveDialog(null);
    }
    private void actionPerformedExit() {
        System.exit(0);
    }

    private void actionPerformedNominalitzar(){

    }
    /*private void actionPerformedIdentifierVerbs(){
        nmlt.setEnabled(true);
    }*/
    private void actionPerformedRedefinir() {
        PVC.ViewRedefinir();
    }
    private void actionPerformedIdiom() {
        PVC.ViewIdiom();
    }
    private void actionPerformedHelp(String s) {
        PVC.ViewHelp(s);
    }
    private void actionPerformedSetting(){
        PVC.ViewSettings();
    }
    /*private void actionPerformedDictionary(){
        PVC.ViewDictionary();
    }*/
    public void setVisible() {
        setVisible(true);
    }
}
